package com.smcs.xmloper.commonData;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.smcs.idcmanager.model.Idc;
import com.smcs.utils.DateUtils;
import com.thoughtworks.xstream.XStream;

public class UploadDataXmlOper {
	
	/**
	 * 创建基础查询上报数据 
	 */
	public static String createQueryListXml(Idc idc){
		QueryResult queryResult = new QueryResult();
		queryResult.setIdcInfo(idc);
		
		UploadData uploadData = new UploadData();
		
//		uploadData.setNewInfo(newInfo);
//		uploadData.setUpdateInfo(updateInfo);
//		uploadData.setDeleteInfo(deleteInfo);
		uploadData.setQueryResult(queryResult);
		uploadData.setTimeStamp(DateUtils.getTimestampCurrentTime(new Date()));
		
		XStream xs = new XStream();
		xs.processAnnotations(UploadData.class);
		return xs.toXML(uploadData);
	}
	
	/**
	 * 解析基础数据新增/更新数据
	 */
	public static UploadData parseIdcUserInfo(File file){
		XStream xs = new XStream();
		xs.processAnnotations(UploadData.class);
		try {
			FileInputStream fis = new FileInputStream(file);
			return (UploadData) xs.fromXML(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 解析基础数据新增/更新数据，参数为字符串
	 * @throws UnsupportedEncodingException 
	 */
	public static UploadData parseIdcUserInfo(String xmlString) {
		UploadData uploadData = null;
		
		XStream xs = new XStream();
		xs.processAnnotations(UploadData.class);
		InputStream myIn;
		try {
			myIn = new ByteArrayInputStream(xmlString.getBytes("utf-8"));
			return (UploadData) xs.fromXML(myIn);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
//		try {
//			Document document = DocumentHelper.parseText(xmlString);
//			writeFile(new File("d:/test.xml"), document.asXML());
//			
//			myIn = new ByteArrayInputStream(xmlString.getBytes("utf-8"));
//			uploadData = (UploadData) xs.fromXML(myIn);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		return uploadData;
	}
	
	/**
	 * 写文件的方法
	 * @param file 目标文件
	 * @param content 文件内容
	 * @return 是否正常写文件
	 */
	public static void writeFile(File file, String content) {
		FileWriter fileWriter = null;
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			fileWriter = new FileWriter(file);
			fileWriter.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
